package atom.tree;


public class Tree<T> {
	private ContentProvider<T> contentProvider;
	private T root;

	public void setContentProvider(ContentProvider<T> contentProvider) {
		this.contentProvider = contentProvider;
	}

	public void setRoot(T root) {
		this.root = root;
	}

	public void printToConsole() {
		assertContentProviderNotNull();
		assetRootNotNull();
		System.out.println(contentProvider.getLabel(root));
		if (contentProvider.hasChildren(root)) {
			for (T node : contentProvider.getChildren(root)) {
				recursivePrint(node);
			}
		}
		System.out.println("\n\nfinish");
	}
	
	private void recursivePrint(T node) {
		String indent = createIndentation(contentProvider.getLevel(node));
		System.out.println(indent+contentProvider.getLabel(node));
		if (contentProvider.hasChildren(node)) {
			for (T kid : contentProvider.getChildren(node)) {
				recursivePrint(kid);
			}
		}
	}
	
	private String createIndentation(int level) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < level; i++) {
			sb.append(" ");
		}
		return sb.toString();
	}

	private void assertContentProviderNotNull() {
		if (contentProvider == null) {
			throw new RuntimeException("ContentProvider can not be null");
		}
	}

	private void assetRootNotNull() {
		if (root == null) {
			throw new RuntimeException("Root can not be null");
		}
	}
}
